package management

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/jsrccb/nachuan/common"
)

func initUploadFileApi(r *mux.Router) {
	s := r.PathPrefix("/upload").Subrouter()
	s.HandleFunc("/user", handleUserFileUpload)
	s.HandleFunc("/attorney", handleAttorneyFileUpload)
}

func handleUserFileUpload(resp http.ResponseWriter, req *http.Request) {

	var (
		err           error
		fdir          string
		filenameslice []string
	)

	req.ParseMultipartForm(32 << 20)
	file, handler, err := req.FormFile("uploadfile")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()

	fmt.Fprintf(resp, "%v", handler.Header)

	fdir = "./uploadfile/user/" + time.Now().Format("20060102") + "/"

	if PathExists(fdir) == false {
		err = os.MkdirAll(fdir, os.ModePerm)
	}
	filenameslice = strings.Split(handler.Filename, ".")
	randomname := common.BuildUUID()
	handler.Filename = randomname + "." + filenameslice[len(filenameslice)-1]
	f, err := os.OpenFile(fdir+handler.Filename, os.O_WRONLY|os.O_CREATE, 0755)

	if err != nil {
		fmt.Println("file open fail" + err.Error())
		return
	}

	defer f.Close()
	io.Copy(f, file)

	if bytes, err := common.BuildResponse(0, "success", (fdir + handler.Filename)[1:]); err == nil {
		resp.Write(bytes)
	}

	return

}
func handleAttorneyFileUpload(resp http.ResponseWriter, req *http.Request) {

	var (
		err           error
		fdir          string
		filenameslice []string
	)

	req.ParseMultipartForm(32 << 20)
	file, handler, err := req.FormFile("uploadfile")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()

	fmt.Fprintf(resp, "%v", handler.Header)

	fdir = "./uploadfile/attorney/" + time.Now().Format("20060102") + "/"

	if PathExists(fdir) == false {
		err = os.MkdirAll(fdir, os.ModePerm)
	}
	filenameslice = strings.Split(handler.Filename, ".")
	randomname := common.BuildUUID()
	handler.Filename = randomname + "." + filenameslice[len(filenameslice)-1]
	f, err := os.OpenFile(fdir+handler.Filename, os.O_WRONLY|os.O_CREATE, 0755)

	if err != nil {
		fmt.Println("file open fail" + err.Error())
		return
	}

	defer f.Close()
	io.Copy(f, file)

	if bytes, err := common.BuildResponse(0, "success", (fdir + handler.Filename)[1:]); err == nil {
		resp.Write(bytes)
	}

	return
}
func PathExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

// func UploadToMinio(objectName string, file *multipart.FileHeader, contentType string) error {
// 	// 初使化 minio client对象

// 	minioClient, err := minio.New(G_config.MINIO_ENDPOINT, G_config.MINIO_ACCESS_KEY, G_config.MINIO_SECRET_KEY, true)
// 	if err != nil {
// 		return err
// 	}

// 	// 创建一个叫xxxx的存储桶
// 	err = minioClient.MakeBucket(G_config.Minio_bucketName, "user")
// 	if err != nil {
// 		// 检查存储桶是否已经存在。
// 		exists, err := minioClient.BucketExists(G_config.Minio_bucketName)
// 		if err == nil && exists {
// 			log.Printf("Bucket:%s is already exist\n", G_config.Minio_bucketName)
// 		} else {
// 			return err
// 		}
// 	}
// 	log.Printf("Successfully created bucket: %s\n", G_config.Minio_bucketName)

// 	src, err1 := file.Open()
// 	if err1 != nil {
// 		return err1
// 	}
// 	defer src.Close()

// 	// 使用PutObject上传一个zip文件
// 	_, err2 := minioClient.PutObject(G_config.Minio_bucketName, objectName, src, -1, minio.PutObjectOptions{ContentType: contentType})
// 	if err2 != nil {
// 		return err2
// 	}

// 	return nil
// }
